<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../js/vue.min.js"></script>
    <script src="../js/axios.min.js"></script>
</head>
<body>
<div id="a">
    <!-- ref="cb1" 给combo的命名
        通过控制台  v.$refs.cb1 获取到 combo 元素
     -->
    <combo url="http://47.106.66.89:2222/easy/books/list"
           value="id"
           display="bookname"
           selected="4"
           ref="cb1"
           @mychange="showBookId"></combo>
        <!-- 没有定义插槽 -->
    <br>
    <combo url="http://47.106.66.89:2222/easy/dm_product/list"
           value="id"
           display="pname"
           selected="4"
           ref="cb2">
        <!-- 组件标签内部的元素 是默认插槽内容, 如果没有定义,则使用slot标签内的元素 -->
        <option value="0">-- 请选择 --</option>
    </combo>
    <hr>
    选择图书编号:{{selectedBookId}}


</div>

<script>
    Vue.component("combo", {
        props: ["url", "value", "display", "selected"],
        data() {
            return {list: [], selectedValue : null}
        },
        created() {
            // 将传入的 selected 赋值给 v-model 属性
            this.selectedValue = this.selected;
            axios.get(this.url).then(res => {
                this.list = res.data;
                // 过滤书名为空的垃圾数据
                this.list = this.list.filter(
                    item => item[this.display] != null && item[this.display] > ""
                );
            })
        },
        template: `
            <select v-model="selectedValue"
                    @change="$emit( 'mychange', selectedValue )">
                <slot>
                    <option></option>
                </slot>
                <option v-for="item in list" :value="item[value]"
                    v-bind:['selected']="item[value]==selected">
                    {{item[display]}}
                </option>
            </select>
        `
    })

    //  直接给父组件赋值, 不推荐
    //  @change="$parent.selectedBookId = selectedValue"
    // $emit( 'mychange', selectedValue ) 向父组件传递事件
    var v = new Vue({
        el: "#a",
        data : {selectedBookId : ""},
        methods : {
            showBookId( bookId){
                this.selectedBookId = bookId;
            }
        }
    });


</script>


</body>
</html>